package com.wang.interview.threads;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author: wang
 * @date: 2021/7/24 21:18
 * @description: hashMap 线程不安全，会存在并发修改异常，使用读写分离锁
 * 注意： lock 的解锁应该放在 finally 里
 */
public class ReadAndWriteLockTest {
    Map<String,String> map = new HashMap<String,String>();
    ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    public void add(String a) throws InterruptedException {
        readWriteLock.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName()+"开始写入");
            TimeUnit.MILLISECONDS.sleep(100);
            map.put(a, "bbb");
            System.out.println(Thread.currentThread().getName()+"写入完成");
        } finally {
            readWriteLock.writeLock().unlock();
        }
    }

    public String get(String a) throws InterruptedException {
        readWriteLock.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName()+"开始获取");
            TimeUnit.MILLISECONDS.sleep(300);
            String aaa = map.get(a);
            System.out.println(Thread.currentThread().getName()+"获取完成");
            return aaa;
        } finally {
            readWriteLock.readLock().unlock();
        }
    }

    public static void main(String[] args) {
        ReadAndWriteLockTest rawt = new ReadAndWriteLockTest();
        for (int i = 0; i < 5; i++) {
            final  int x = i;
            new Thread(()->{
                try {
                    rawt.add(x+"");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            },x+"").start();
        }
        for (int i = 0; i < 5; i++) {
            final int x = i;
            new Thread(()->{
                try {
                    rawt.get(x+"");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            },x+"").start();
        }
    }
}
